"""
病历管理 API 端点
"""
from typing import List
from uuid import UUID
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
import json

from app.db.session import get_db
from app.crud.record import RecordCRUD
from app.core.parser import MedicalRecordParser
from app.schemas.common import ResponseModel, PaginatedResponse, PaginationParams
from app.schemas.record import (
    MedicalRecordResponse,
    MedicalRecordDetailResponse,
    MedicalRecordListItem,
    MedicalRecordCreate,
    MedicalRecordUpdate,
    RecordUploadResponse,
    RecordQueryParams
)
from app.core.logger import app_logger


router = APIRouter()


@router.post("/upload", response_model=ResponseModel[RecordUploadResponse])
async def upload_records(
    files: List[UploadFile] = File(...),
    db: AsyncSession = Depends(get_db)
):
    """
    批量上传病历JSON文件
    """
    success_records = []
    errors = []
    
    for file in files:
        try:
            # 检查文件类型
            if not file.filename.endswith('.json'):
                errors.append({
                    'filename': file.filename,
                    'error': '仅支持 JSON 格式文件'
                })
                continue
            
            # 读取文件内容
            content = await file.read()
            raw_data = json.loads(content.decode('utf-8'))
            
            # 验证数据
            is_valid, validation_errors = MedicalRecordParser.validate(raw_data)
            if not is_valid:
                errors.append({
                    'filename': file.filename,
                    'error': f"数据验证失败: {'; '.join(validation_errors)}"
                })
                continue
            
            # 解析数据
            parsed_data = MedicalRecordParser.parse(raw_data)
            
            # 提取用药和医嘱数据
            medications_data = parsed_data.pop('_medications', [])
            instructions_data = parsed_data.pop('_instructions', [])
            
            # 创建病历记录
            record_create = MedicalRecordCreate(**parsed_data)
            db_record = await RecordCRUD.create(
                db=db,
                record_data=record_create,
                medications_data=medications_data,
                instructions_data=instructions_data
            )
            
            success_records.append(MedicalRecordResponse.model_validate(db_record))
            
        except json.JSONDecodeError as e:
            errors.append({
                'filename': file.filename,
                'error': f'JSON 解析失败: {str(e)}'
            })
        except Exception as e:
            app_logger.error(f"上传文件失败 {file.filename}: {e}", exc_info=True)
            errors.append({
                'filename': file.filename,
                'error': f'处理失败: {str(e)}'
            })
    
    result = RecordUploadResponse(
        success_count=len(success_records),
        failed_count=len(errors),
        records=success_records,
        errors=errors
    )
    
    return ResponseModel(
        code=200 if len(success_records) > 0 else 400,
        message=f"成功上传 {len(success_records)} 条病历，失败 {len(errors)} 条",
        data=result
    )


@router.get("/list", response_model=ResponseModel[PaginatedResponse[MedicalRecordListItem]])
async def get_records_list(
    patient_name: str = None,
    department: str = None,
    has_assessment: bool = None,
    page: int = 1,
    page_size: int = 10,
    db: AsyncSession = Depends(get_db)
):
    """
    获取病历列表（支持分页和筛选）
    """
    # 构建查询参数
    query_params = RecordQueryParams(
        patient_name=patient_name,
        department=department,
        has_assessment=has_assessment
    )
    
    # 查询数据
    records, total = await RecordCRUD.get_list(
        db=db,
        params=query_params,
        page=page,
        page_size=page_size
    )
    
    # 批量查询评估状态
    from sqlalchemy import select, func
    from app.models.assessment import Assessment
    
    record_ids = [record.id for record in records]
    assessment_stmt = (
        select(Assessment.record_id)
        .where(Assessment.record_id.in_(record_ids))
        .distinct()
    )
    assessment_result = await db.execute(assessment_stmt)
    assessed_record_ids = {row[0] for row in assessment_result.all()}
    
    # 转换为列表项
    items = []
    for record in records:
        item_dict = {
            'id': record.id,
            'patient_name': record.patient_name,
            'patient_gender': record.patient_gender,
            'patient_age': record.patient_age,
            'department': record.department,
            'visit_date': record.visit_date,
            'diagnosis': record.diagnosis,
            'created_at': record.created_at,
            'has_assessment': record.id in assessed_record_ids
        }
        items.append(MedicalRecordListItem(**item_dict))
    
    # 构建分页响应
    paginated_result = PaginatedResponse(
        total=total,
        page=page,
        page_size=page_size,
        items=items,
        total_pages=(total + page_size - 1) // page_size
    )
    
    return ResponseModel(data=paginated_result)


@router.get("/{record_id}", response_model=ResponseModel[MedicalRecordDetailResponse])
async def get_record_detail(
    record_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    获取病历详情
    """
    record = await RecordCRUD.get_by_id(db, record_id)
    
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="病历不存在"
        )
    
    return ResponseModel(data=MedicalRecordDetailResponse.model_validate(record))


@router.put("/{record_id}", response_model=ResponseModel[MedicalRecordResponse])
async def update_record(
    record_id: UUID,
    update_data: MedicalRecordUpdate,
    db: AsyncSession = Depends(get_db)
):
    """
    更新病历
    """
    record = await RecordCRUD.update(db, record_id, update_data)
    
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="病历不存在"
        )
    
    return ResponseModel(
        message="病历更新成功",
        data=MedicalRecordResponse.model_validate(record)
    )


@router.delete("/{record_id}", response_model=ResponseModel[dict])
async def delete_record(
    record_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    删除病历（软删除）
    """
    success = await RecordCRUD.delete(db, record_id)
    
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="病历不存在"
        )
    
    return ResponseModel(
        message="病历删除成功",
        data={'record_id': str(record_id)}
    )


@router.get("/statistics/summary", response_model=ResponseModel[dict])
async def get_statistics(
    db: AsyncSession = Depends(get_db)
):
    """
    获取统计信息
    """
    stats = await RecordCRUD.get_statistics(db)
    return ResponseModel(data=stats)

